package com.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.excel.entity.DemoData;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:ExcelController
 * Package:com.excel.controller
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/7/9 - 22:04
 * @Version:v1.0
 */
@RestController
@RequiredArgsConstructor
public class ExcelController {

    private List<DemoData> data() {
        List<DemoData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setTitle("字符串" + i);
            data.setDateTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    @GetMapping("/excel")
    public void excel(HttpServletResponse response) throws IOException {
        //文件需要设置成StandardCharsets.ISO_8859_1编码，否则导出的excel文件名乱码
        String excelName = new String("浏览器导出excel.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + excelName );
        List<DemoData> list = data();
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, DemoData.class)
                .sheet("sheet1")
                .doWrite(list);
    }

    @GetMapping("/import")
    public List<DemoData> excelImport(MultipartFile file) throws IOException {
        List<DemoData> list = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), DemoData.class, new PageReadListener<DemoData>(dataList -> {
            for (DemoData demoData : dataList) {
                DemoData entity = JSONObject.parseObject(JSONObject.toJSONString(demoData), DemoData.class);
                list.add(entity);
            }
        })).sheet().doRead();
        return list;
    }
}
